package com.sgcc.manager.cmd;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.filefilter.RegexFileFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <br>Title:TODO 类标题
 * <br>Description:TODO 类功能描述
 * <br>Author:王腾龙
 * <br>Date:Mar 4, 2015
 * http://www.cnblogs.com/nkxyf/archive/2012/12/13/2815978.html
 * http://liuyuru.iteye.com/blog/806365
 */
@Controller
public class CmdDemo {
	@RequestMapping("cmd")
	public Object cmd(Model model){
		return "cmd";
	}
	
	@RequestMapping(value="executCMD",method=RequestMethod.POST)
	public void cmdString(String cmd,Model model,HttpSession session,HttpServletRequest request, HttpServletResponse response){
		cmd=cmd.replace('\\', '/');
		System.out.println("cmd命令--->"+cmd);
		String newCmd=regex(cmd);
		String result=cmd(newCmd);
		System.out.println("----执行完成----");
		if(result.isEmpty()){
			result="[执行完成]";
		}
//		String ut_utf8Toiso = new String(result.getBytes("UTF-8"),"UTF-8");
//		System.out.println("utf-8--->"+ut_utf8Toiso);
		response.setContentType("text/html");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(result);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

//		return ut_utf8Toiso;
	}
	
	private static String cmd(String cmdString){
		BufferedReader br = null;
		String result="";
        try {
            Process p = Runtime.getRuntime().exec("cmd.exe /c "+cmdString);
                br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                    result+=line+"\n";
                }
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                result="执行出错！";
                return result;
            } finally {
 
                if (br != null) {
                    try {
                        br.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    public static void main(String[] args) {
    	String string="C:/Program Files/MySQL/MySQL Server 5.5/bin/mysqld.exe";
    	regex(string);
//    	Scanner sc = new Scanner(System.in); 
//    	String scString=sc.nextLine();
//    	while (!"exit".equals(scString)) {
//    		System.out.println("cmd命令--->"+scString);
//    		cmd(scString);
//    		System.out.println("----执行完成----");
//    		sc = new Scanner(System.in); 
//        	scString=sc.next();
//		}
//    	cmd("net user");
    }
    
    /**
     * 
     * <br>Description:替换路径名称字符串中的空格为 "空格"
     * @param string
     * @return
     */
	private static String regex(String str) {
		String string=str;
		String regexString=string;
		String regex="\\/(\\w+ )+\\w+(\\/|\\.\\w+)";
		Pattern pattern=Pattern.compile(regex);
		Matcher matcher=pattern.matcher(regexString);
		int length=0;
		while (matcher.find()) {
//			String temp = string.substring(matcher.start(),matcher.end());
			String temp = matcher.group();
			System.out.println("匹配："+temp);
			String newtemp=temp.replace(" ", "\" \"");
			string=string.replaceAll(temp, newtemp);
			string.indexOf(newtemp);
			regexString=string.substring(string.indexOf(newtemp)+newtemp.length()-1);
			System.out.println("regex--"+regexString);
			matcher.reset(regexString);
		}
		System.out.println("最终的string--"+string);
//		String newCmd=cmd.replace(" ", "\" \"");
		return string;
		
	} 
}